<template>
  <div>
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/bank/questions' }">题目池</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="subjectTitle">
<!--   筛选   -->
      <el-collapse style="margin-left: 5%;" v-model="activeNames" @change="handleChange">
        <el-collapse-item title="筛选题目" name="1">
          <div class="check-box">科目：
            <el-radio-group v-model="searchForm.subjectId" @change="getKnowledgePointBySubjectSearch()">
              <el-radio v-for="item in subjects"
              :key="item.id"
              :label="item.id">{{item.name}}</el-radio>
            </el-radio-group>
          </div>
          <div class="check-box" v-if="searchForm.subjectId !== null">知识点：
            <el-radio-group v-model="searchForm.knowledgePointId">
              <el-radio v-for="item in knowledgePoints"
                        :key="item.id"
                        :label="item.id">{{item.name}}</el-radio>
            </el-radio-group>
          </div>
          <div class="check-box">题型：
            <el-radio-group v-model="searchForm.questionType">
              <el-radio v-for="item in types"
                        :key="item.value"
                        :label="item.value">{{item.name}}</el-radio>
            </el-radio-group>
          </div>
          <div class="check-box">题目类型：
            <el-radio-group v-model="searchForm.examQuestion">
              <el-radio :label="true">考试题</el-radio>
              <el-radio :label="false">练习题</el-radio>
            </el-radio-group>
          </div>
          <el-link type="info" @click="clearSearch">清空</el-link>
        </el-collapse-item>
      </el-collapse>
      <el-button type="primary" style="margin-left:10%; width: 80%; height: 50px;" @click="search">搜索题目</el-button>
      <el-button type="primary" style="margin-left:10%; width: 80%; height: 50px;" @click="addDialogVisible = true">增加题目</el-button>
    </div>
    <div style="width: 90%; margin-left: 5%; margin-top: 10px;">
      <el-table
        :data="questionList"
        style="width: 100%">
        <el-table-column
          prop="stemShow"
          label="题目">
        </el-table-column>
        <el-table-column
          prop="subject"
          label="科目"
          width="130">
        </el-table-column>
        <el-table-column
          prop="knowledgePoint"
          label="知识点"
          width="130">
        </el-table-column>
        <el-table-column
          prop="teacherNumber"
          label="老师"
          width="130">
        </el-table-column>
        <el-table-column
          label="题型"
          width="130">
          <template slot-scope="scope">
            <span>{{transferType(scope.row.questionType)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="题目类型"
          width="130">
          <template slot-scope="scope">
            <span>{{scope.row.examQuestion?'考试题':'练习题'}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="更新时间"
          prop="updateTimeShow"
          width="140">
        </el-table-column>
        <el-table-column
          label="操作"
          width="140">
          <template slot-scope="scope" style="display: grid; grid-template-columns: 33% 33% 33%">
            <el-link type="info" @click="detailQuestion(scope.row)">查看</el-link>
            <el-link type="primary" @click="updateQuestion(scope.row)">修改</el-link>
            <el-link type="danger" @click="deleteQuestion(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          layout="total, prev, pager, next"
          :page-size="pagination.page_size"
          :current-page="pagination.index"
          :total="pagination.total"
          @current-change="changePage">
        </el-pagination>
      </div>
    </div>
<!--  增加题目  -->
    <el-dialog
      title="增加题目"
      :visible.sync="addDialogVisible"
      width="50%"
      center>
      <el-form ref="addForm" :model="questionAdd" label-width="auto" label-position="left">
        <!--   选择题型   -->
        <el-form-item label="题型" prop="questionType">
          <el-select v-model="questionAdd.questionType" placeholder="请选择题型" class="form-item">
            <el-option
              v-for="item in types"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="题目类型">
          <el-radio-group v-model="questionAdd.examQuestion">
            <el-radio :label="true">考试题</el-radio>
            <el-radio :label="false">练习题</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="科目" prop="subjectId">
          <el-select v-model="questionAdd.subjectId" placeholder="请选择" @change="getKnowledgePointBySubject()">
            <el-option
              v-for="item in subjects"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="questionAdd.subjectId !== ''" label="知识点" prop="knowledgePointId">
          <el-select v-model="questionAdd.knowledgePointId" placeholder="请选择">
            <el-option
              v-for="item in knowledgePoints"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="题干" prop="stem">
          <el-input type="textarea" v-model="questionAdd.stem"></el-input>
        </el-form-item>

        <!--    单选题目    -->
        <el-form-item v-if="questionAdd.questionType === 'radio' || questionAdd.questionType === 'multiple'" label="选项A">
          <el-input v-model="questionAdd.options.A"></el-input>
        </el-form-item>
        <el-form-item v-if="questionAdd.questionType === 'radio' || questionAdd.questionType === 'multiple'" label="选项B">
          <el-input v-model="questionAdd.options.B"></el-input>
        </el-form-item>
        <el-form-item v-if="questionAdd.questionType === 'radio' || questionAdd.questionType === 'multiple'" label="选项C">
          <el-input v-model="questionAdd.options.C"></el-input>
        </el-form-item>
        <el-form-item v-if="questionAdd.questionType === 'radio' || questionAdd.questionType === 'multiple'" label="选项D">
          <el-input v-model="questionAdd.options.D"></el-input>
        </el-form-item>

        <!--    答案    -->
        <el-form-item v-if="questionAdd.questionType !== 'shortAnswer'" label="答案">
          <el-input v-model="questionAdd.answer"></el-input>
        </el-form-item>
        <el-form-item v-if="questionAdd.questionType === 'shortAnswer'" label="答案">
          <el-input type="textarea" v-model="questionAdd.answer"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addQuestion()">确 定</el-button>
        </span>
    </el-dialog>
<!--  预览题目  -->
    <el-dialog
      title="查看题目"
      :visible.sync="detailDialogVisible"
      width="50%"
      center>
      <div class="detail">
        <div class="title"><i class="el-icon-s-order"></i>科目</div>
        <span class="text">{{questionDetail.subject}}</span>
        <div class="title"><i class="el-icon-s-order"></i>知识点</div>
        <span class="text">{{questionDetail.knowledgePoint}}</span>
        <div class="title"><i class="el-icon-s-order"></i>题目</div>
        <span class="text">{{questionDetail.stem}}</span>
        <!--   单选选项   -->
        <div class="text" v-if="questionDetail.questionType === 'radio' || questionDetail.questionType === 'multiple'">A.{{questionDetail.options.A}}</div>
        <div class="text" v-if="questionDetail.questionType === 'radio' || questionDetail.questionType === 'multiple'">B.{{questionDetail.options.B}}</div>
        <div class="text" v-if="questionDetail.questionType === 'radio' || questionDetail.questionType === 'multiple'">C.{{questionDetail.options.C}}</div>
        <div class="text" v-if="questionDetail.questionType === 'radio' || questionDetail.questionType === 'multiple'">D.{{questionDetail.options.D}}</div>
        <div class="title"><i class="el-icon-s-order"></i>答案</div>
        <div class="text">{{questionDetail.answer}}</div>
      </div>
    </el-dialog>
<!--  修改题目  -->
    <el-dialog
      title="修改题目"
      :visible.sync="updateDialogVisible"
      width="50%"
      center>
      <el-form ref="addForm" :model="questionUpdate" label-width="auto" label-position="left">
        <el-form-item label="题干" prop="stem">
          <el-input type="textarea" v-model="questionUpdate.stem" @input="inputChange"></el-input>
        </el-form-item>

        <!--    单选题目    -->
        <el-form-item v-if="questionUpdate.questionType === 'radio' || questionUpdate.questionType === 'multiple'" label="选项A">
          <el-input v-model="questionUpdate.options.A"></el-input>
        </el-form-item>
        <el-form-item v-if="questionUpdate.questionType === 'radio' || questionUpdate.questionType === 'multiple'" label="选项B">
          <el-input v-model="questionUpdate.options.B"></el-input>
        </el-form-item>
        <el-form-item v-if="questionUpdate.questionType === 'radio' || questionUpdate.questionType === 'multiple'" label="选项C">
          <el-input v-model="questionUpdate.options.C"></el-input>
        </el-form-item>
        <el-form-item v-if="questionUpdate.questionType === 'radio' || questionUpdate.questionType === 'multiple'" label="选项D">
          <el-input v-model="questionUpdate.options.D"></el-input>
        </el-form-item>

        <!--    答案    -->
        <el-form-item v-if="questionUpdate.questionType !== 'shortAnswer'" label="答案">
          <el-input v-model="questionUpdate.answer"></el-input>
        </el-form-item>
        <el-form-item v-if="questionUpdate.questionType === 'shortAnswer'" label="答案">
          <el-input type="textarea" v-model="questionUpdate.answer"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateConfirm()">确 定</el-button>
        </span>
    </el-dialog>
<!--  删除题目  -->
    <el-dialog
      title="提示"
      :visible.sync="deleteDialogVisible"
      width="30%">
      <span>确定删除题目吗，此操作无法撤销！</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="deleteConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import {questionSearchAll, findSubjectsByHouse, getKnowledgePoints, questionSearch} from '../../../api/questions'
import {addQuestion, deleteQuestion, updateQuestion} from '../../../api/questionDetail'

export default {
  name: 'Questions',
  data () {
    return {
      // 预览题目
      detailDialogVisible: false,
      questionDetail: {},
      // 删除题目
      deleteDialogVisible: false,
      // 修改题目
      updateDialogVisible: false,
      questionUpdate: {
        answer: '',
        createTime: '',
        examQuestion: true,
        knowledgePointId: '',
        questionStem: '',
        questionType: '',
        subjectId: '',
        teacherId: 0,
        updateTime: '',
        // 辅助属性
        stem: '',
        options: {
          A: '',
          B: '',
          C: '',
          D: ''
        }
      },
      // 增加题目
      addDialogVisible: false,
      questionAdd: {
        answer: '',
        createTime: '',
        examQuestion: true,
        knowledgePointId: '',
        questionStem: '',
        questionType: '',
        subjectId: '',
        teacherId: 0,
        updateTime: '',
        // 辅助属性
        stem: '',
        options: {
          A: '',
          B: '',
          C: '',
          D: ''
        }
      },
      types: [
        {
          name: '单选',
          value: 'radio'
        },
        {
          name: '多选',
          value: 'multiple'
        },
        {
          name: '填空',
          value: 'filling'
        },
        {
          name: '简答',
          value: 'shortAnswer'
        }
      ],
      subjects: [],
      knowledgePoints: [],
      // 分页信息
      pagination: {
        page_size: 10,
        index: 1,
        total: 100
      },
      // 筛选条件
      activeNames: [],
      searchForm: {
        subjectId: null,
        knowledgePointId: null,
        teacherId: null,
        questionType: null,
        examQuestion: null,
        updateTime: null
      },
      // 表格显示
      questionList: [
        {
          answer: 'A',
          createTime: '2022-03-24 14:18:34',
          id: 1,
          knowledgePointId: 2,
          questionStem: '{"stem":"192.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。","options":{"A":"14 14","B":"16 14","C":"254 6","D":"14 62"}}',
          questionType: 'radio',
          subjectId: 1,
          teacherId: 1,
          updateTime: '2022-03-24 14:18:34',
          examQuestion: false,
          stem: '92.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。',
          options: {
            A: '',
            B: '',
            C: '',
            D: ''
          }
        },
        {
          answer: 'A',
          createTime: '2022-03-24 14:18:34',
          id: 1,
          knowledgePointId: 2,
          questionStem: '{"stem":"192.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。","options":{"A":"14 14","B":"16 14","C":"254 6","D":"14 62"}}',
          questionType: 'radio',
          subjectId: 1,
          teacherId: 1,
          updateTime: '2022-03-24 14:18:34',
          examQuestion: false,
          stem: '92.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。'
        },
        {
          answer: 'A',
          createTime: '2022-03-24 14:18:34',
          id: 1,
          knowledgePointId: 2,
          questionStem: '{"stem":"192.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。","options":{"A":"14 14","B":"16 14","C":"254 6","D":"14 62"}}',
          questionType: 'radio',
          subjectId: 1,
          teacherId: 1,
          updateTime: '2022-03-24 14:18:34',
          examQuestion: false,
          stem: '92.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。'
        }
      ]
    }
  },
  mounted () {
    this.getAllQuestions()
    this.getSubjectByHouse()
  },
  methods: {
    // 获取所有题目
    getAllQuestions () {
      let parameter = {
        page_size: this.pagination.page_size,
        index: this.pagination.index - 1,
        house: sessionStorage.getItem('teacherHouse')
      }
      questionSearchAll(parameter).then(res => {
        if (res.data.errorCode === 0) {
          console.log(res.data)
          this.questionList = res.data.data.list
          this.pagination.total = res.data.data.total
          // 转化格式
          for (let i = 0; i < this.questionList.length; i++) {
            this.questionList[i].stemShow = this.transferForm(this.questionList[i])
            this.questionList[i].stem = JSON.parse(this.questionList[i].questionStem).stem
            this.questionList[i].options = JSON.parse(this.questionList[i].questionStem).options
            this.questionList[i].updateTimeShow = this.transferTime(this.questionList[i])
          }
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 翻页
    changePage (val) {
      this.pagination.index = val
      this.getAllQuestions()
    },
    // 转化格式
    transferForm (questionDetail) {
      let stem = JSON.parse(questionDetail.questionStem)
      let temp = stem.stem
      var count = 0
      for (var i = 0; i < temp.length; i++) {
        // eslint-disable-next-line no-control-regex
        if (temp.charAt(i).replace(/[^\x00-\xff]/g, 'rr').length > 1) {
          count += 2
        } else {
          count += 1
        }
        if (count >= 27) {
          return temp.slice(0, i) + '...'
        }
      }
      return temp
    },
    transferTime (questionDetail) {
      return questionDetail.updateTime.slice(0, 10)
    },
    transferType (type) {
      switch (type) {
        case 'radio': return '单选'
        case 'multiple': return '多选'
        case 'filling': return '填空'
        case 'shortAnswer': return '简答'
        default: return 'error'
      }
    },
    // 增加题目
    addQuestion () {
      let that = this
      let flag = that.questionAdd.stem !== '' &&
        that.questionAdd.answer !== '' &&
        that.questionAdd.knowledgePointId !== '' &&
        that.questionAdd.questionType !== '' &&
        that.questionAdd.subjectId !== ''

      if (flag) {
        const stem = {
          stem: that.questionAdd.stem,
          options: {
            A: that.questionAdd.options.A,
            B: that.questionAdd.options.B,
            C: that.questionAdd.options.C,
            D: that.questionAdd.options.D
          }
        }
        that.questionAdd.questionStem = JSON.stringify(stem)
        that.questionAdd.teacherId = sessionStorage.getItem('teacherId')
        console.log(that.questionAdd)
        // 发送请求
        addQuestion(that.questionAdd).then(res => {
          if (res.data.errorCode === 0) {
            that.$message({
              message: '增加题目成功！',
              type: 'success'
            })
            that.addDialogVisible = false
            that.questionAdd = {
              answer: '',
              createTime: '',
              examQuestion: true,
              knowledgePointId: '',
              questionStem: '',
              questionType: '',
              subjectId: '',
              teacherId: 0,
              updateTime: '',
              // 辅助属性
              stem: '',
              options: {
                A: '',
                B: '',
                C: '',
                D: ''
              }
            }
            that.getAllQuestions()
          } else {
            that.$message.error(res.data.message)
          }
        })
      } else {
        this.$message.error('请填写完整信息')
      }
    },
    // 通过学院获取科目
    getSubjectByHouse () {
      findSubjectsByHouse(sessionStorage.getItem('teacherHouse')).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          this.subjects = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 通过科目获取知识点（增加窗口）
    getKnowledgePointBySubject () {
      this.questionAdd.knowledgePointId = ''
      getKnowledgePoints(this.questionAdd.subjectId).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          this.knowledgePoints = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 通过科目获取知识点（更新窗口）
    getKnowledgePointBySubjectUpdate () {
      console.log(this.questionUpdate.subjectId)
      this.questionUpdate.knowledgePointId = ''
      getKnowledgePoints(this.questionUpdate.subjectId).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          this.knowledgePoints = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 预览题目
    detailQuestion (questionDetail) {
      this.questionDetail = questionDetail
      this.detailDialogVisible = true
    },
    // 更新题目
    updateQuestion (questionDetail) {
      this.questionUpdate = questionDetail
      this.updateDialogVisible = true
    },
    updateConfirm () {
      const stem = {
        stem: this.questionUpdate.stem,
        options: {
          A: this.questionUpdate.options.A,
          B: this.questionUpdate.options.B,
          C: this.questionUpdate.options.C,
          D: this.questionUpdate.options.D
        }
      }
      this.questionUpdate.questionStem = JSON.stringify(stem)
      this.questionUpdate.updateTime = this.questionUpdate.updateTime.slice(0, 10) + 'T' + this.questionUpdate.updateTime.slice(11, 19) + 'Z'
      this.questionUpdate.createTime = this.questionUpdate.createTime.slice(0, 10) + 'T' + this.questionUpdate.updateTime.slice(11, 19) + 'Z'
      updateQuestion(this.questionUpdate).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          this.$message.success('修改成功')
          this.updateDialogVisible = false
          this.getAllQuestions()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 删除题目
    deleteQuestion (questionDetail) {
      this.questionDetail = questionDetail
      this.deleteDialogVisible = true
    },
    deleteConfirm () {
      deleteQuestion([this.questionDetail.id]).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          this.$message.success('删除成功')
          this.deleteDialogVisible = false
          this.getAllQuestions()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 用于textArea修复bug
    inputChange () {
      this.$forceUpdate()
    },
    // 通过科目获取知识点（查找）
    getKnowledgePointBySubjectSearch () {
      getKnowledgePoints(this.searchForm.subjectId).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          this.knowledgePoints = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 搜索
    handleChange (val) {
      console.log(val)
    },
    // 搜索
    clearSearch () {
      this.searchForm = {
        subjectId: null,
        knowledgePointId: null,
        teacherId: null,
        questionType: null,
        examQuestion: null,
        updateTime: null
      }
      this.getAllQuestions()
    },
    search () {
      this.pagination = {
        page_size: 5,
        index: 1,
        total: 100
      }
      let parameter = {
        page_size: this.pagination.page_size,
        index: this.pagination.index - 1,
        house: sessionStorage.getItem('teacherHouse'),
        subjectId: this.searchForm.subjectId,
        knowledgePointId: this.searchForm.knowledgePointId,
        questionType: this.searchForm.questionType,
        examQuestion: this.searchForm.examQuestion
      }
      questionSearch(parameter).then(res => {
        if (res.data.errorCode === 0) {
          console.log(res.data)
          this.questionList = res.data.data.list
          this.pagination.total = res.data.data.total
          // 转化格式
          for (let i = 0; i < this.questionList.length; i++) {
            this.questionList[i].stemShow = this.transferForm(this.questionList[i])
            this.questionList[i].stem = JSON.parse(this.questionList[i].questionStem).stem
            this.questionList[i].options = JSON.parse(this.questionList[i].questionStem).options
            this.questionList[i].updateTimeShow = this.transferTime(this.questionList[i])
          }
        } else {
          this.$message.error(res.data.message)
        }
      })
    }
  }
}
</script>

<style scoped>
  .breadcrumb {
    padding: 20px;
  }

  .subjectTitle {
    font-size: 16px;
    font-weight: bold;
    margin: 0 20px;
    display: grid;
    grid-template-columns: 80% 10% 10%;
  }

  .title {
    margin-top: 10px;
    margin-left: 10px;
    font-size: 15px;
    font-weight: bolder;
  }

  .text {
    margin-top: 10px;
    margin-bottom: 10px;
    margin-left: 20px;
    font-size: 15px;
  }

  .check-box {
    margin-bottom: 5px;
    text-align: left;
  }
</style>
